from typing import *
from sortedcontainers import SortedDict


class Solution:

    def continuousSubarrays(self, nums: List[int]) -> int:
        l = 0
        sd = SortedDict()
        ans = 0
        for i, num in enumerate(nums):
            if num in sd:
                sd[num] += 1
            else:
                sd[num] = 1
            while abs(num -
                      min(sd.keys())) > 2 or abs(num -
                                                 max(sd.keys())) > 2 and l < i:
                sd[nums[l]] -= 1
                if sd[nums[l]] == 0:
                    sd.pop(nums[l])
                l += 1
            ans += i - l + 1
        return ans


so = Solution()
print(so.continuousSubarrays([5, 4, 2, 4]))
print(so.continuousSubarrays([1,2,3]))
